import Taro, { Component, useEffect, useState } from '@tarojs/taro';
import { View, Image, ScrollView } from '@tarojs/components';
import { connect } from '@tarojs/redux';
import DelIcon from '../../static/address/icon_del.png';
import { getProvince } from '../../services/address';
import { setAddress } from '../../actions/counter';
import classnames from 'classnames';

import './index.scss';


/**
 * 地址组件
 * @param {func} closeItem 关闭弹窗, 有参数时应该就是3个值都选择了
 * @param {Boolean} isSelected 弹窗是否显示
 * @param {Array} defaultvalue 初始地址显示 用在selectList
 */
function Address(props) {
  const { isSelected } = props;

  const [ list, setList ] = useState([]);
  const [ selectList, setSelectList ] = useState([]);
  const [ addressIndex, setAddressIndex ] = useState(0);
  const [ isFirst, setIsFirst ] = useState(0);

  useEffect(() => {
    getProvince().then(res => {
      const { setAddress } = props;
      setAddress({
        0: res
      });
      setList(res)
    })
  }, []);

  useEffect(() => {
    if (!isFirst && props.defaultvalue && props.defaultvalue.length) {
      setIsFirst(true);
      setSelectList(props.defaultvalue);
    }
  }, [props.defaultvalue]);




  function selectDom(res) {
    selectList[res.region_type - 1] = {
      id: res.id,
      region_name: res.region_name
    };
    setSelectList(selectList);
    if (res.region_type === 3) {
      setAddressIndex(2);
      props.closeItem({
        launch_province_name: selectList[0].region_name,
        province: selectList[0].id,
        launch_city_name: selectList[1].region_name,
        city: selectList[1].id,
        launch_region_name: selectList[2].region_name,
        region: selectList[2].id,
      });
      return false;
    } else {
      if (selectList.length > res.region_type) {
        selectList.length = res.region_type;
        setSelectList(selectList);
      }
      setAddressIndex(res.region_type);
    }
    if (!props.address[res.id]) {
      getProvince({
        parent_id: res.id
      }).then(ele => {
        const data = {};
        data[res.id] = ele;
        props.setAddress(data);
        setList(ele)
      })
    } else {
      setList(props.address[res.id]);
    }
  }

  function changeTab(index) {
    let id = 0;
    if (index) {
      id = selectList[index - 1].id;
    } else {
      id = 0;
    }
    selectList.length = index + 1;
    setSelectList(selectList);
    if (!props.address[id]) {
      getProvince(id).then(ele => {
        const data = {};
        data[id] = ele;
        props.setAddress(data);
        setList(ele)
      })
    } else {
      setList(props.address[id] || []);
    }
    setAddressIndex(index);
  }

  function closeItem() {
    console.log(selectList)
    let data = {}
    if (selectList.length === 3) {
      data = {
        launch_province_name: selectList[0].region_name,
        province: selectList[0].id,
        launch_city_name: selectList[1].region_name,
        city: selectList[1].id,
        launch_region_name: selectList[2].region_name,
        region: selectList[2].id,
      }
    } else if (selectList.length === 2) {
      data = {
        launch_province_name: selectList[0].region_name,
        province: selectList[0].id,
        launch_city_name: selectList[1].region_name,
        city: selectList[1].id,
      }
    } else if (selectList.length === 1) {
      data = {
        launch_province_name: selectList[0].region_name,
        province: selectList[0].id,
      }
    }
    props.closeItem({
      ...data
    })
    // Taro.showToast({
    //   title: '请选择地址',
    //   icon: 'none'
    // })
  }


    return (
      isSelected ? (
        <View className="address-item">
          <View className="space"></View>
          <View className="address">
            <View className="title">
              收货地址
              <Image src={DelIcon} onClick={closeItem} className="del-icon" />
            </View>
            <View className="content">
              {
                selectList.map((res, index) => (
                  <View key={res.id} onClick={() => changeTab(index)} className={classnames({
                    'addr': true,
                    'select-addr': index === addressIndex
                  })} >{res.region_name}</View>
                ))
              }
              {
                selectList.length < 3 ? (
                  <View className={classnames({
                    'tip': true,
                    'tips': selectList.length === addressIndex
                  })}>请选择</View>
                ) : null
              }
            </View>
            <ScrollView scrollY={true} className="addr-scroll">
              {
                list.map(res => (
                  <View key={res.id} onClick={() => selectDom(res)} className={classnames({
                    'addr-content': true,
                    'select-addr-content': selectList[addressIndex] && selectList[addressIndex].id === res.id
                  })}>{res.region_name}</View>
                ))
              }
            </ScrollView>
          </View>
        </View>
      ) : null
    )
}

export default connect(
  ({ counter: { address } }) => ({
    address,
  }),
  dispatch => ({
    setAddress(payload) {
      dispatch(setAddress(payload));
    },
  })
)(Address)
